/*
Copyright (c) 2009, Joseph J. Bergeron
All rights reserved.

Redistribution  and  use  in  source  and  binary  forms,  with  or  without  
modification,  are  permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
     this list of conditions and the following disclaimer in the documentation 
     and/or other materials provided with the distribution.
    * Neither the name of the creators nor the names of its contributors
      may be used to endorse or promote products derived from this software 
      without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package hatkins.display
{
	import flash.display.BitmapData;
	import flash.geom.Point;
	import flash.geom.Rectangle;
		
	/**
	 * A rectangular grid of bitmap tiles.
	 */
	public class Patch
	{
		private var _bitmapData:BitmapData;
		private var _tileWidth:int;
		private var _tileHeight:int;
		private var _numberOfTilesWide:int;
		private var _numberOfTilesTall:int;
		private var _indices:Array;
		private var _cachedTileRect:Rectangle;
		private var _cachedDestPoint:Point;
		
		/**
		 * Create a Patch
		 */
		public function Patch(bitmapData:BitmapData, tileWidth:int, tileHeight:int, numberOfTilesWide:int, numberOfTilesTall:int) {
			_bitmapData = bitmapData;
			_numberOfTilesWide = numberOfTilesWide;
			_numberOfTilesTall = numberOfTilesTall;
			_tileWidth = tileWidth;
			_tileHeight = tileHeight;
			_indices = new Array(numberOfTilesWide * numberOfTilesTall);
			_cachedTileRect = new Rectangle();
			_cachedDestPoint = new Point();
			for (var i:int=0; i<_indices.length; ++i) {
				_indices[i] = 0; // invisible tile
			}
		}
		
		/**
		 * Set the tile index at a grid position
		 */
		public function setTileIndex(xPos:int, yPos:int, index:int):void {
			if (xPos>=0 && xPos<_numberOfTilesWide && yPos>=0 && yPos<_numberOfTilesTall && index>=0) {
				var tileSheetTilesWide:int = int(_bitmapData.width / _tileWidth);
				var tileXPixel:int = (index % tileSheetTilesWide) * _tileWidth;
				var tileYPixel:int = int(index / tileSheetTilesWide) * _tileHeight;
				
				// internally indices are encoded to save on calculations
				_indices[(yPos * _numberOfTilesWide) + xPos] = (tileXPixel << 16) | tileYPixel;
			}
		}
		
		/**
		 *  Set the tile index at a pixel location
		 */
		public function setTileIndexAtPixel(pixelX:int, pixelY:int, index:int):void {
			setTileIndex(int(pixelX / _tileWidth), int(pixelY / _tileHeight), index);
		}
		
		/**
		 * Get the tile index at a grid position
		 */
		public function getTileIndex(xPos:int, yPos:int):int {
			var index:int = -1;
			if (xPos>=0 && xPos<_numberOfTilesWide && yPos>=0 && yPos<_numberOfTilesTall) {
				var encodedIndex:int = int(_indices[(yPos * _numberOfTilesWide) + xPos]);
				var tileSheetTilesWide:int = int(_bitmapData.width / _tileWidth);
				var tileXPixel:int = encodedIndex >> 16;
				var tileYPixel:int = encodedIndex & 0xFFFF;
				index = int(tileYPixel / _tileHeight) * tileSheetTilesWide + int(tileXPixel / _tileWidth);
			}
			return index;
		}
		
		/**
		 *  Get the tile index at a pixel location
		 */
		public function getTileIndexAtPixel(pixelX:int, pixelY:int):int {
			return getTileIndex(int(pixelX / _tileWidth), int(pixelY / _tileHeight));
		}

		/**
		 * Draw pixels to a destination BitmapData
		 */
		public function blit(destBitmapData:BitmapData, destX:int, destY:int, sourceX:int, sourceY:int, sourceWidth:int, sourceHeight:int):void {
		 	 	
		 	if (sourceX < 0) {
				destX -= sourceX;
				sourceWidth = Math.max(sourceWidth + sourceX, 0);
				sourceX = 0;
			}
			

			if (sourceY < 0) {
				destY -= sourceY;
				sourceHeight = Math.max(sourceHeight + sourceY, 0);
				sourceY = 0;
			}
			
			sourceX = Math.min(widthInPixels, sourceX);
			sourceY = Math.min(heightInPixels, sourceY);
			
			sourceWidth = Math.min(widthInPixels - sourceX, sourceWidth);
			sourceHeight = Math.min(heightInPixels - sourceY, sourceHeight);

			if (sourceWidth > 0 && sourceHeight > 0) {
				_blit(destBitmapData, destX, destY, sourceX, sourceY, sourceWidth, sourceHeight);
			}
		 }
		 
		//private function _blit(destBitmapData:BitmapData, destPoint:Point, sourceRect:Rectangle):void {
		private function _blit(destBitmapData:BitmapData, destX:int, destY:int, sourceX:int, sourceY:int, sourceWidth:int, sourceHeight:int):void {

			// upper, left corner tile index positions
			var xTileStart:int = int(sourceX / _tileWidth);
			var yTileStart:int = int(sourceY / _tileHeight);

			// lower, right corner tile index positions
			var xTileLast:int = int((sourceX + sourceWidth - 1) / _tileWidth);
			var yTileLast:int = int((sourceY + sourceHeight - 1) / _tileHeight);

			// left, top edge pixel offset into the tile
			var leftXPixelOffset:int = sourceX % _tileWidth;
			var topYPixelOffset:int = sourceY % _tileWidth;
		
			// right, bottom pixel width and height of tiles
			var rightPixelWidth:int = 1 + (sourceX + sourceWidth - 1) % _tileWidth;
			var bottomPixelHeight:int = 1 + (sourceX + sourceHeight - 1) % _tileHeight;

			var index:int = int(_indices[(yTileStart * _numberOfTilesWide) + xTileStart]);

			var xTile:int = xTileStart;
			var yTile:int = yTileStart;
		
			_cachedTileRect.x = (index >> 16) + leftXPixelOffset;
			_cachedTileRect.y =	(index & 0xFFFF) + topYPixelOffset;
			_cachedTileRect.width = xTileStart==xTileLast ? rightPixelWidth : _tileWidth - leftXPixelOffset;
			_cachedTileRect.height = yTileStart==yTileLast ? bottomPixelHeight : _tileHeight - topYPixelOffset;
		
			_cachedDestPoint.x = destX;
			_cachedDestPoint.y = destY;
			
			// top, left tile
			destBitmapData.copyPixels(
				_bitmapData,
				_cachedTileRect,
				_cachedDestPoint);
				
			++xTile;
			_cachedDestPoint.x += _cachedTileRect.width;
			_cachedTileRect.width = _tileWidth;
			
			var rowPos:int = yTile * _numberOfTilesWide;
			
			// top, edge
			for (; xTile<xTileLast; ++xTile) {
				index = int(_indices[rowPos + xTile]);
				_cachedTileRect.x = index >> 16;
				_cachedTileRect.y = (index & 0xFFFF) + topYPixelOffset;
			
				destBitmapData.copyPixels(
					_bitmapData,
					_cachedTileRect,
					_cachedDestPoint);
			
				_cachedDestPoint.x += _cachedTileRect.width;
			}
			
			// upper, right corner
			if (xTile==xTileLast) {
				index = int(_indices[rowPos + xTile]);
				_cachedTileRect.x = index >> 16;
				_cachedTileRect.y = (index & 0xFFFF) + topYPixelOffset;
				_cachedTileRect.width = rightPixelWidth;
				
				destBitmapData.copyPixels(
					_bitmapData,
					_cachedTileRect,
					_cachedDestPoint);
			
			}
			
			_cachedDestPoint.y += _cachedTileRect.height;
			
			++yTile;
			_cachedTileRect.height = _tileHeight;

			// middle portion
			for (; yTile<yTileLast; ++yTile) {
				
				// left edge
				rowPos = yTile * _numberOfTilesWide;
				index = int(_indices[rowPos + xTileStart]);
				_cachedTileRect.x = (index >> 16) + leftXPixelOffset;
				_cachedTileRect.y = (index & 0xFFFF);
				_cachedTileRect.width = xTileStart==xTileLast ? rightPixelWidth : _tileWidth - leftXPixelOffset,
				_cachedDestPoint.x = destX;				

				destBitmapData.copyPixels(
					_bitmapData,
					_cachedTileRect,
					_cachedDestPoint);
					
				_cachedDestPoint.x += _cachedTileRect.width;
				_cachedTileRect.width = _tileWidth;
				
				// middle run
				for (xTile = xTileStart + 1; xTile<xTileLast; ++xTile) {
					index = int(_indices[rowPos + xTile]);
					_cachedTileRect.x = (index >> 16);
					_cachedTileRect.y = (index & 0xFFFF);
					
					destBitmapData.copyPixels(
						_bitmapData,
						_cachedTileRect,
						_cachedDestPoint);
					
					_cachedDestPoint.x += _tileWidth;
				}
				
				// right edge
				if (xTile==xTileLast) {
					index = int(_indices[rowPos + xTile]);
					_cachedTileRect.x = index >> 16;
					_cachedTileRect.y = index & 0xFFFF;
					_cachedTileRect.width = rightPixelWidth;

					destBitmapData.copyPixels(
						_bitmapData,
						_cachedTileRect,
						_cachedDestPoint);
				}
				
				_cachedDestPoint.y += _tileHeight;
			}
			
			// bottom row
			if (yTile==yTileLast) {
				
				// lower, left corner
				rowPos = yTile * _numberOfTilesWide;
				index = int(_indices[rowPos + xTileStart]);
				_cachedTileRect.x = (index >> 16) + leftXPixelOffset;
				_cachedTileRect.y = index & 0xFFFF;
				_cachedTileRect.width = xTileStart==xTileLast ? rightPixelWidth : _tileWidth - leftXPixelOffset;
				_cachedTileRect.height = bottomPixelHeight;
				_cachedDestPoint.x = destX;
				
				destBitmapData.copyPixels(
					_bitmapData,
					_cachedTileRect,
					_cachedDestPoint);
				
				_cachedDestPoint.x += _cachedTileRect.width;
				_cachedTileRect.width = _tileWidth;
				
				// bottom run
				for (xTile = xTileStart + 1; xTile<xTileLast; ++xTile) {
					index = int(_indices[rowPos + xTile]);
					_cachedTileRect.x = (index >> 16);
					_cachedTileRect.y = (index & 0xFFFF);
					
					destBitmapData.copyPixels(
						_bitmapData,
						_cachedTileRect,
						_cachedDestPoint);
					
					_cachedDestPoint.x += _tileWidth;
				}
				
				// bottom, right corner
				if (xTile==xTileLast) {
					index = int(_indices[rowPos + xTile]);
					_cachedTileRect.x = (index >> 16);
					_cachedTileRect.y = (index & 0xFFFF);
					_cachedTileRect.width = rightPixelWidth;
					_cachedTileRect.height = bottomPixelHeight;
				
					destBitmapData.copyPixels(
						_bitmapData,
						_cachedTileRect,
						_cachedDestPoint);
				}
			}
		}

		/**
		 * The 'tilesheet' BitmapData
		 */
		public function get bitmapData():BitmapData {
			return _bitmapData;
		}
		
		/**
		 * The width of the Patchs in pixels
		 */
		public function get widthInPixels():int {
			return _numberOfTilesWide * _tileWidth;
		}
		
		/**
		 * The height of the Patch in pixels
		 */
		public function get heightInPixels():int {
			return _numberOfTilesTall * _tileHeight;
		}
	}
}